package com.bcu.alumnus.aop;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
@Component
@Aspect
public class WebLogAop {
    //引入日志配置
    private   Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 定义一个切入点 只拦截controller.
     * 解释下：
     * ~ 第一个 * 代表任意修饰符及任意返回值.
     * ~ 第二个 * 定义在web包或者子包
     * ~ 第三个 * 任意方法
     * ~ .. 匹配任意数量的参数.
     */
    @Pointcut("execution(* com.bcu.alumnus.controller.*.*(..))")
    public void logPointcut() {
    }

    //around(和上面的方法名一样)
    @org.aspectj.lang.annotation.Around("logPointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        logger.info("======Method  start======");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        long start = System.currentTimeMillis();
        try {
            Object result = joinPoint.proceed();
            long end = System.currentTimeMillis();
            logger.info("请求地址:" + request.getRequestURI());
            logger.info("用户IP:" + request.getRemoteAddr());
            logger.info("方法: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
//            logger.info("入参: " + new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL)
//                    .writeValueAsString(joinPoint.getArgs()[0]));
            logger.info("入参："+Arrays.toString(joinPoint.getArgs()));
//            logger.info("返回："+joinPoint.);
            logger.info("执行时间: " + (end - start) + " ms!");
            logger.info("======Method  End======");
            return result;
        } catch (Throwable e) {
            long end = System.currentTimeMillis();
            logger.info("URL:" + request.getRequestURI());
            logger.info("IP:" + request.getRemoteAddr());
            logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
            logger.info("执行时间: " + (end - start) + " ms!");
            logger.info("=======Method  End=======");
            throw e;
        }
    }
}
